import {useState,useEffect} from 'react'

const useKeyPress = (keyCode) => {

  const [keyPressed, setkeyPressed] = useState(false)

  const handleKeyDown = (e) => {
    if(e.keyCode === keyCode) {
      setkeyPressed(true)
    }

  }

  const handleKeyUp = (e) => {
    if(e.keyCode === keyCode) {
      setkeyPressed(false)
    }
  }

  useEffect(() => {
    document.addEventListener('keydown',handleKeyDown);
    document.addEventListener('keyup',handleKeyUp)
    return () => {
      document.removeEventListener('keydown',handleKeyDown);
      document.removeEventListener('keyup',handleKeyUp);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return keyPressed
}

export default useKeyPress